import {
    Button,
    HStack,
    Input,
    InputGroup,
    InputLeftElement,
    InputRightElement,
    Stack,
    Text,
    useColorModeValue,
    VStack,
    Popover,
    PopoverTrigger,
    PopoverContent,
    PopoverHeader,
    PopoverBody,
    PopoverFooter,
    PopoverArrow,
    PopoverCloseButton,
    PopoverAnchor,
    Portal,
    Toast,
    useToast,
    ButtonGroup,
    useDisclosure,
    Box,
    FormLabel,
    InputRightAddon,
    InputLeftAddon,
    Textarea,
} from '@chakra-ui/react'
import {
    ArrowForwardIcon,
    CalendarIcon,
    CheckIcon,
    DeleteIcon,
    EditIcon,
    EmailIcon,
    PhoneIcon,
    SearchIcon
} from "@chakra-ui/icons";
import ManageSearchBar from "../../../components/ManageSearchBar.jsx";
import React, {useEffect, useState} from "react";
import {useAuth} from "../../../hooks/index.js";
import {useNavigate} from "react-router-dom";

import {
    Drawer,
    DrawerBody,
    DrawerFooter,
    DrawerHeader,
    DrawerOverlay,
    DrawerContent,
    DrawerCloseButton,
} from '@chakra-ui/react'
import dayjs from 'dayjs';
import customParseFormat from 'dayjs/plugin/customParseFormat';
import {handleResult, handleResultNoRoute} from "../../../api/result.js";
import {
    delStudent,
    findByName,
    getAllStudent,
    getAllStudentPage,
    getStudentCount,
    saveStudent
} from "../../../api/student.js";
import {getAllOrderPage, getOrderCount} from "../../../api/order.js";

dayjs.extend(customParseFormat);
const dateFormat = 'YYYY-MM-DD';

export default function StudentManagePage() {
    const navigator = useNavigate()
    const toast = useToast()
    const {authInfo} = useAuth()

    // 数据获取
    const [students, setStudents] = useState([])
    const [total, setTotal] = useState(0) // 总条数
    useEffect(() => {
        console.log(authInfo)
        // 请求数据
        getAllStudentPage({page: 0, size: 6}).then((data) => {
            console.log(data)
            setStudents(data.data)
        })
        getStudentCount().then(r => {
            setTotal(parseInt(r.data))
            console.log(total)
        })
    }, []);

    // ManageSearchBar states
    const [value, setValue] = useState('')
    let timer = new Date()
    const [startDate, setStartDate] = useState(timer.toLocaleDateString())
    const [endDate, setEndDate] = useState(timer.toLocaleDateString())

    let searchItem = {
        placeholder: '学生名称',
        value,
        onChange: (e) => {
            setValue(e.target.value)
        },
        onClick: (e) => {
            if (value === '') {
                getAllStudent().then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setStudents(r.data)
                })
                return
            }
            findByName(value).then(r => {
                handleResultNoRoute(r, toast, '', '查询成功')
                setStudents(r.data)
            })
        }
    }
    let dateSearchItem = {
        onChange: (date, dateString) => {
            console.log(date, dateString)
            setStartDate(dateString[0])
            setEndDate(dateString[1])
        },
        onClick: (e) => {
            console.log(startDate, endDate)
        }
    }
    // 当前页码
    const [curIdx, setCurIdx] = useState(1);
    let pageSearchItem = {
        total: (Math.floor(total / 6) + 1), curIdx,
        onChange: (e) => {
            setCurIdx(e.target.value)
        },
        onLeftClick: () => {
            console.log(curIdx)
            if (curIdx > 1) {
                setCurIdx((curIdx - 1))
                return
            }
            toast({
                title: `已到达第一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onRightClick: () => {
            if (curIdx < (Math.floor(total / 6) + 1)) {
                setCurIdx((curIdx + 1))
                return
            }
            toast({
                title: `已到达最后一页!`,
                status: 'warning',
                position: 'top',
                isClosable: true,
            })
        },
        onClick: () => {
            console.log(total)
            getAllStudentPage({page: curIdx, size: 6})
                .then(r => {
                    handleResultNoRoute(r, toast, '', '查询成功')
                    setStudents(r.data)
                })
        }
    }

    // 添加按钮 弹出drawer
    const {isOpen, onOpen, onClose} = useDisclosure()
    // 用于弹出时聚焦
    const firstField = React.useRef()

    function onAddClick() {
        onOpen()
    }

    // drawer里的表单的数据
    const [name, setName] = useState('')

    // 操作栏
    function handleDelClick(id) {
        delStudent(id).then(r => {
            handleResult(r, toast, '', '删除成功')
        })
    }

    function handleUptClick(id) {
        navigator(`/student/${parseInt(id)}`)
    }

    return (
        <Stack
            align={'start'}
            justify={'start'}
            spacing={4}
            mb={6}
            className={useColorModeValue('', 'dark')}
        >
            <ManageSearchBar
                pageSearchItem={pageSearchItem}
                onAddClick={onAddClick}
                searchItem={searchItem}
                dateSearchItem={dateSearchItem}/>
            <div className={"table-container " + useColorModeValue('', 'dark')}>
                <table className="table table-hover">
                    <thead>
                    <tr>
                        <th>名称</th>
                        <th>就医数</th>
                        <th>操作</th>
                    </tr>
                    </thead>
                    <tbody>
                    {
                        // doctors.map((item,i)=>{
                        students.map((item) => (
                            <tr key={item.id}>
                                <td>{item.name}</td>
                                <td>{item.number}</td>
                                <td>
                                    <Stack direction='row' spacing={4}>
                                        <Button
                                            onClick={handleUptClick.bind(this, item.id)}
                                            leftIcon={<EditIcon/>} size='sm'
                                            colorScheme='teal' variant='solid'>
                                            编辑
                                        </Button>
                                        <Popover
                                            placement='right'
                                            closeOnBlur={false}
                                        >
                                            <PopoverTrigger>
                                                <Button
                                                    leftIcon={<DeleteIcon/>} size='sm'
                                                    colorScheme='red' variant='solid'>
                                                    删除
                                                </Button>
                                            </PopoverTrigger>
                                            <PopoverContent>
                                                <PopoverHeader fontWeight='semibold'>
                                                    Confirmation
                                                </PopoverHeader>
                                                <PopoverArrow/>
                                                <PopoverCloseButton/>
                                                <PopoverBody>
                                                    你确定要删除该条数据吗?
                                                </PopoverBody>
                                                <PopoverFooter display='flex' justifyContent='flex-end'>
                                                    <ButtonGroup size='sm'>
                                                        <Button
                                                            onClick={() => handleDelClick(item.id)}
                                                            colorScheme='red'>确认</Button>
                                                    </ButtonGroup>
                                                </PopoverFooter>
                                            </PopoverContent>
                                        </Popover>
                                    </Stack>
                                </td>
                            </tr>
                        ))
                    }
                    </tbody>
                </table>
                <Drawer
                    size={'md'}
                    isOpen={isOpen}
                    placement='right'
                    initialFocusRef={firstField}
                    onClose={onClose}
                >
                    <DrawerOverlay/>
                    <DrawerContent>
                        <DrawerCloseButton/>
                        <DrawerHeader borderBottomWidth='1px'>
                            创建医生信息
                        </DrawerHeader>

                        <DrawerBody>
                            <Stack spacing='24px'>
                                <Box>
                                    <FormLabel htmlFor='username'>名称</FormLabel>
                                    <Input
                                        ref={firstField}
                                        id='username'
                                        value={name}
                                        onChange={(e) => setName(e.target.value)}
                                        placeholder='输入学生姓名'
                                    />
                                </Box>
                            </Stack>
                        </DrawerBody>

                        <DrawerFooter borderTopWidth='1px'>
                            <Button variant='outline' mr={3} onClick={onClose}>
                                取消
                            </Button>
                            <Button onClick={() => {
                                console.log(name)
                                saveStudent({name}).then(r =>
                                    handleResult(r, toast, null, '添加成功')
                                )
                            }} colorScheme='blue'>提交</Button>
                        </DrawerFooter>
                    </DrawerContent>
                </Drawer>
            </div>
        </Stack>
    )
}